package si.dejan.picflip.model
{
	import com.adobe.webapis.flickr.Photo;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	/** Holds data about a single flickr Photo */
	public class PhotoProxy extends Proxy implements IProxy
	{
		public const TYPE_SMALL:String = "small";
		public const TYPE_BIG:String = "big";
		
		private var _imageSize:String;
		
		public function get loadCompletedEvent():String
		{
			if(getImageId() == "")
				throw new Error("photo object is null");
			return "photoLoadCompleted" + getImageId();
		}
		
		private var loader:Loader;
		public function PhotoProxy(proxyName:String, data:Photo)
		{
			super(proxyName, data);
		}
		
		public function getImageId():String
		{
			return photo.id;
		}
		
		/** Loads url, send notification LOAD_COMPLETED, body = loader.content */
		private function load(url:String):void
		{
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoadComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleLoadIOError);
			loader.load(new URLRequest(url));			
		}
		
		private function handleLoadComplete(event:Event):void
		{
			sendNotification(loadCompletedEvent, event.currentTarget.content, _imageSize); 
		}
		
		private function handleLoadIOError(event:IOErrorEvent):void
		{
			trace("Error", event.text);
		}
		
		public function getLoader():Loader
		{
			return loader;
		}
		
		public function loadSmallImage():void
		{
			_imageSize = TYPE_SMALL;
			load('http://static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_m.jpg');
		}
		
		public function loadBigImage():void
		{
			_imageSize = TYPE_BIG;
			load('http://static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_b.jpg');
		}
		
		private function get photo():Photo
		{
			return data as Photo;
		}
	}
}